package cn._2dland.uploader.sixrooms;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;

import cn._2dland.uploader.CountingMultipartRequestEntity;
import cn._2dland.uploader.UploadClient;
import cn._2dland.uploader.UploadHandler;
import cn._2dland.uploader.UploadTask;
import cn._2dland.uploader.UserPassPair;
import cn._2dland.uploader.utils.Logger;

public class SixRoomsClient extends UploadClient {
	public SixRoomsClient(String user, String pass) {
		super(user, pass);
		Logger.writec("6cn上传器初始化...");
	}

	public SixRoomsClient(UserPassPair pair) {
		this(pair.getUsername(), pair.getPassword());
	}

	@Override
	public boolean login() {
		try {
			Logger.writec("登录帐号: " + username + " ...");
			PostMethod loginPost = new PostMethod("http://6.cn/login.php");
			// 填写参数
			loginPost.addParameter("action", "login");
			loginPost.addParameter("back", "1");
			loginPost.addParameter("next_action", "http://6.cn");
			loginPost.addParameter("username", username);
			loginPost.addParameter("passwd", password);

			int respCode = client.executeMethod(loginPost);

			loginPost.releaseConnection();

			bLogin = (respCode == 302);
			if(!bLogin)
				throw new Exception("登录失败...");

			Logger.writec("登录成功!");
		}
		catch (Exception e) {
			bLogin = false;
			e.printStackTrace(System.err);
		}
		return bLogin;
	}

	public boolean upload(UploadTask task) {
		if(!(task instanceof SixRoomsTask))
			return false;
		SixRoomsTask sixTask = (SixRoomsTask)task;
		boolean isOK = false;

		// 获取metter_id
		String metterID = null;
		do{
			metterID = getMetterID();
		}while(metterID == null);

		try{
			Logger.writec("开始上传文件: " + sixTask.file.getName());
			Logger.writec("METTER_ID = " + metterID);

			PostMethod uploadPost = new PostMethod("http://upload.6.cn/upload.php?UPLOAD_METTER_ID=" + metterID);
			uploadPost.addRequestHeader("Referer", "http://6.cn/user/upload.php");
			Part[] parts = {
				new StringPart("UPLOAD_METTER_ID", metterID, "utf-8"),
				new StringPart("act", "upload", "utf-8"),
				new StringPart("MAX_FILE_SIZE", "314572800", "utf-8"),
				new StringPart("tags", sixTask.tags, "utf-8"),
				new FilePart("userfile", sixTask.getFileName(), sixTask.file),
				new StringPart("title", sixTask.title, "utf-8"),
				new StringPart("memo", sixTask.descript, "utf-8"),
				new StringPart("cid[]", String.valueOf(sixTask.cid), "utf-8"),
				new StringPart("status", String.valueOf(sixTask.status), "utf-8")
			};
			uploadPost.setRequestEntity(new CountingMultipartRequestEntity(parts, uploadPost.getParams(), task.file.length(), new UploadHandler()));
			int respCode = client.executeMethod(uploadPost);
			String body = uploadPost.getResponseBodyAsString();

			// 释放资源
			uploadPost.releaseConnection();

			// 判断上传是否成功
			if(respCode != HttpStatus.SC_OK)
				throw new Exception("上传失败！");
			if(body.indexOf("上传成功，请等待系统自动处理") < 0)
				throw new Exception("上传失败！");

			isOK = true;
		}
		catch (Exception e) {
			isOK = false;
			e.printStackTrace(System.err);
		}
		return isOK;
	}

	private String getMetterID() {
		String metterID = null;
		try {
			GetMethod metterGet = new GetMethod("http://6.cn/user/upload.php");

			int respCode = client.executeMethod(metterGet);
			if(respCode >= 400)
				throw new Exception("请求失败！");
			InputStream is = metterGet.getResponseBodyAsStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
			for(String line; (line=br.readLine())!=null; ){
				if(line.matches("^<input type=\"hidden\"  name=\"UPLOAD_METTER_ID\" value=\"\\d+\".*>$")){
					metterID = line.substring(line.indexOf("value=\"")+7, line.lastIndexOf("\""));
					break;
				}
			}
			br.close();
			is.close();
			metterGet.releaseConnection();
		}
		catch (Exception e) {
			metterID = null;
			e.printStackTrace(System.err);
		}
		return metterID;
	}
}
